package com.itheima.tanhua.server.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.commons.holder.TokenHolderUserId;
import com.itheima.tanhua.dubbo.service.TanhuaService;
import com.itheima.tanhua.dubbo.service.UserService;
import com.itheima.tanhua.model.domain.UserInfo;
import com.itheima.tanhua.model.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author H Monster
 */
@RestController
@RequestMapping("/tanhua")
public class TanhuaController {

    @DubboReference
    private UserService userService;

    @DubboReference
    private TanhuaService tanhuaService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/todayBest")
    public TodayBestVo todayBest() {

        String userId = TokenHolderUserId.get();
        UserInfo myUserInfo = userService.getUserInfoById(userId);

        // 查询当前用户所在城市
        String city = myUserInfo.getCity();

        // 查询与当前用户同城的用户(随机获取)
        UserInfo todayBestInfo = tanhuaService.randomUserByCity(userId, city);

        // 分割数据
        TodayBestVo vo = new TodayBestVo();
        String tags = todayBestInfo.getTags();

        List<String> tagList = new ArrayList<>();
        if (StringUtils.isNotEmpty(tags)) {
            tagList = Arrays.asList(tags.split(","));
        }
        // 组装数据
        BeanUtils.copyProperties(todayBestInfo, vo);
        vo.setTags(tagList);

        // 随机缘分值
        vo.setFateValue(RandomUtil.randomInt(90, 99));

        // 复制id
        String id = todayBestInfo.getId();
        vo.setId(Integer.parseInt(id));

        return vo;
    }

    @GetMapping("/recommendation")
    public RecommendationVo recommend(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer pageSize) throws Exception {
        // 步骤一：获取我的id
        String userId = TokenHolderUserId.get();

        // 步骤二：通过我的id获取我当前的坐标位置
        List<Point> geop = redisTemplate.boundGeoOps("geo").position(userId);
        if (CollUtil.isEmpty(geop)) {
            throw new Exception("数据为空");
        }

        // 步骤三：获取我的第一组坐标
        double x = geop.get(0).getX();
        double y = geop.get(0).getY();

        // 以我为圆心, 画圆, 获取圆圈内其他用户
        // 参数一: 半径长度
        // 参数二: 半径单位
        Distance distance = new Distance(10, Metrics.KILOMETERS);

        // 设置圆心坐标系
        Point point = new Point(x, y);

        // Circle(参数一: 坐标点, 参数二: 半径)
        Circle circle = new Circle(point, distance);

        RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs();
        args.sortAscending()
                .includeCoordinates()
                .includeDistance()
                .limit(10);

        // 搜索周边的方法 radius(参数一: 圆圈, 参数二: 排序)
        GeoResults<RedisGeoCommands.GeoLocation<String>> geo = redisTemplate.boundGeoOps("geo").radius(circle, args);

        // 根据获取到的用户, 到数据库查询他们的用户信息
        List<String> idList = new ArrayList<>();

        for (GeoResult<RedisGeoCommands.GeoLocation<String>> result : geo) {
            RedisGeoCommands.GeoLocation<String> location = result.getContent();

            // 坐标的名称 (用户id)
            String userIdByPosition = location.getName();

            // 坐标经纬度
            Point point1 = location.getPoint();

            System.out.println(point1);

            Map<String, Object> map = new HashMap<>();
            map.put("name", userIdByPosition);
            map.put("x", point1.getX());
            map.put("y", point1.getY());
            idList.add(userIdByPosition);
        }

        // list (以我为中心, 半径10km内所有的坐标点, 所对应的用户id)
        List<UserInfo> userInfos = tanhuaService.getUserInfoInIds(idList);

        List<RecommendationItemsTagsVo> recommendationItemsTagsVo = new ArrayList<>();
        for (UserInfo userInfo : userInfos) {
            RecommendationItemsTagsVo recommendationItemsTags = new RecommendationItemsTagsVo();
            // 随机缘分值
            userInfo.setFateValue(RandomUtil.randomInt(90, 99));
            // 切割数组
            String[] split = userInfo.getTags().split(",");
            // 添加到数组中
            recommendationItemsTags.setTags(split);
            // 复制
            BeanUtils.copyProperties(userInfo, recommendationItemsTags);
            recommendationItemsTagsVo.add(recommendationItemsTags);
        }
        // 总记录数
        Long counts = 10L;

        // 计算页数
        Long totalPages = counts / pageSize;

        RecommendationVo recommendation = new RecommendationVo();

        // 封装数据并返回
        recommendation.setCounts(counts.intValue());
        recommendation.setPages(totalPages.intValue());
        recommendation.setItems(recommendationItemsTagsVo);
        recommendation.setPage(page);
        recommendation.setPagesize(pageSize);

        return recommendation;

//        查询当前用户所在城市
//        String city = myUserInfo.getCity();
//
//        组装分页条件
//        limit(页码 - 1) * 每页显示条数, 每页显示条数
//        Integer skip = (page - 1) * pageSize;
//
//
//        List<RecommendationItemsTagsVo> list = new ArrayList<>();
//        查询分页数据
//        List<RecommendationItemsVo> recommendList = tanhuaService.getRecommendList(skip, pageSize, city, userId);
//
//        for (RecommendationItemsVo recommendationItemsVo : recommendList) {
//
//            recommendationItemsVo.setFateValue();
//            切割数组
//            String[] split = recommendationItemsVo.getTags().split(",");
//
//            recommendationItemsTags.setTags(split);
//            复制
//            BeanUtils.copyProperties(recommendationItemsVo, recommendationItemsTags);
//            list.add(recommendationItemsTags);
//        }


    }
}

